#include "./SYSTEM/ringbuffer/ringbuff.h"

void RingBuff_Init(RingBuff_t *p)
{
	p->Head = 0;
	p->Tail = 0;
	p->Lenght = 0;
}

void Write_RingBuff_Byte(RingBuff_t *p, u8 data)
{
	if (p->Lenght >= RINGBUFF_MAX_LEN)
		return;
	
	p->RingBuff[p->Tail] = data;
	p->Tail = (p->Tail + 1) % RINGBUFF_MAX_LEN;
	p->Lenght++;
}

u8 Read_RingBuff_Byte(RingBuff_t *p, u8 *pdata)
{
	if (p->Lenght == 0)
		return 1;
	
	*pdata = p->RingBuff[p->Head];
	p->Head = (p->Head + 1) % RINGBUFF_MAX_LEN;
	p->Lenght--;
	return 0;
}

uint32_t RingBuff_Byte_size(RingBuff_t *p)
{
	//if(p->Head <= p->Tail)
	//{
	//	return p->Tail - p->Head;
	//}
	//return p->Lenght + p->Tail - p->Head;
	return p->Lenght;
}

void RingStr_Init(RingStr_t *p)
{
	p->Head = 0;
	p->Tail = 0;
	p->Lenght = 0;	
	
}

void Write_RingStr(RingStr_t *p,u8 *pdata,u16 len)
{
	u8 NeedCnt = 0;
	u8 ResidueCnt = 0;
	u8 i = 0;
	u16 offest = 0;
	
	if (p->Lenght >= RINGSTR_MAX_CNT) 
		return;
	
	NeedCnt = (len % RINGSTR_MAX_LEN) ? (len / RINGSTR_MAX_LEN + 1) : (len / RINGSTR_MAX_LEN);
	
	ResidueCnt = RINGSTR_MAX_CNT - (p->Lenght);
	
	if(ResidueCnt < NeedCnt)
	{
			return;
	}
	else
	{
		for(i = 0;i < NeedCnt;i++)
		{
			if(i == (NeedCnt-1))
			{
				p->RingStr[p->Tail][0] = 0;
				p->RingStr[p->Tail][1] = len - offest;			
				memcpy(p->RingStr[p->Tail] + 2,pdata + offest,len - offest);	
			}
			else
			{
				p->RingStr[p->Tail][0] = 1;
				p->RingStr[p->Tail][1] = RINGSTR_MAX_LEN;
				memcpy( p->RingStr[p->Tail] + 2,pdata + offest,RINGSTR_MAX_LEN);
				offest += RINGSTR_MAX_LEN;
			}	
			
			p->Tail = (p->Tail + 1) % RINGSTR_MAX_CNT;
			p->Lenght++;		
		}
	}
}

u8 Read_RingStr(RingStr_t *p,u8 *pdata,u16 *len)
{
	u8 j = 0;
	u8 tmplen = 0;
	u8 OreFlag = 0;
	*len = 0;
	
	for(j = 0; j < RINGSTR_MAX_CNT;j++)
	{
		if (p->Lenght == 0)
			return 1;
		
		OreFlag = p->RingStr[p->Head][0];
		tmplen  = p->RingStr[p->Head][1];
		
		memcpy(pdata + (*len),p->RingStr[p->Head] + 2, tmplen);

		*len = tmplen +  *len;
		
		p->Head = (p->Head + 1) % RINGSTR_MAX_CNT;
		p->Lenght--;			
		
		if(OreFlag == 0)
			break;	
	}
	return 0;
}


